#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define BUF_SIZE 100

int main()
{
	struct addrinfo hints;
	struct addrinfo * result, * rp;
	int err;
	int sfd;
	FILE* sfp;
	char buf[BUF_SIZE];

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;

	err = getaddrinfo("pop.qq.com", "110", &hints, &result);
	if (err) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(err));
		exit(EXIT_FAILURE);
	}

	for (rp = result; rp != NULL; rp = rp->ai_next) {
		sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
		if (sfd < 0) {
			continue;
		}

		if (connect(sfd, rp->ai_addr, rp->ai_addrlen) == 0) {
			printf("server connected\n");
			break;
		}

		perror("connect");

		close(sfd);
	}
	
	if (!rp) {
		exit(EXIT_FAILURE);
	}

	freeaddrinfo(result);

	sfp = fdopen(sfd, "r+");
	if (!sfp) {
		perror("fdopen");
		exit(EXIT_FAILURE);
	}

	if (fgets(buf, BUF_SIZE, sfp)) {
		printf("S: %s", buf);
	}

	fprintf(sfp, "user QQ号\r\n");

	if (fgets(buf, BUF_SIZE, sfp)) {
		printf("S: %s", buf);
	}

	fprintf(sfp, "pass 授权码\r\n");

	if (fgets(buf, BUF_SIZE, sfp)) {
		printf("S: %s", buf);
	}

	fprintf(sfp, "stat\r\n");

	if (fgets(buf, BUF_SIZE, sfp)) {
		printf("S: %s", buf);
	}

	fprintf(sfp, "quit\r\n");

	if (fgets(buf, BUF_SIZE, sfp)) {
		printf("S: %s", buf);
	}

	fclose(sfp);

	return 0;
}

